﻿using System;
using System.Collections.Generic;
using DB_test.Models;

namespace DB_test
{
    class Diver
    {
        private int id;
        private String Name;
        public List<Jump> Jumps { get; private set; }

        public Diver()
        {
            this.Jumps = new List<Jump>();
        }

        public Diver(string name)
        {
            this.Jumps = new List<Jump>();
            this.Name = name;
        }

        public int Id
        {
            get
            {
                return this.id;
            }
            set
            {
                this.id = value;
                foreach (var jump in this.Jumps)
                    jump.DiverId = this.id;
            }
        }

        public void AddJump(Jump jump)
        {
            jump.DiverId = this.Id;
            this.Jumps.Add(jump);
        }

        public void RemoveJump(Jump jump)
        {
            this.Jumps.Remove(jump);
            JumpMap.RemoveJump(jump);
        }

        public static Diver GetFromDictionary(Dictionary<String, Object> data)
        {
            return new Diver
            {
                Id = (int)data["Id"],
                Name = ((String)data["Name"]).Trim(),
                Jumps = ReadJumpsFromDataBase((int)data["Id"])
            };
        }

        public Dictionary<String, Object> GetDictionary()
        {
            var dictionary = new Dictionary<String, Object>();
            dictionary.Add("Id", Id);
            dictionary.Add("Name", Name);
            return dictionary;
        }

        private static List<Jump> ReadJumpsFromDataBase(int diverId)
        {
            var jumps = new List<Jump>();
            foreach (var data in MyDbConnection.ReadFromDataBase(String.Format("select * from jumps where DiverId={0}", diverId)))
                jumps.Add(Jump.GetFromDictionary(data));
            return jumps;
        }

        public String ToString()
        {
            return String.Format("Id:{0}, Name:{1}", this.Id, this.Name);
        }


        public static string GetIdField()
        {
            return "Id";
        }

        internal void SetName(string p)
        {
            this.Name = p;
        }
    }
}
